import dayjs from 'dayjs';
import { observer } from 'mobx-react-lite';
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import store from '@/store';

import styles from './index.less';

export type RecorderState = 'start' | 'recording' | 'pause' | 'end' | 'ready';
const Index = () => {
  const [state, setState] = useState<RecorderState>('ready');
  const timer = useRef<any>(null);
  const navigate = useNavigate();
  const recorderTime = () => {
    if (state === 'ready') {
      // 第一次开始录制
      setState('recording');
      start();
      store.startRecord();
    }
    if (state === 'recording') {
      setState('pause');
      store.pauseRecord();
      window.console.log('暂停', timer);
      timer.current && clearInterval(timer.current);
      timer.current = null;
    }
    if (state === 'pause') {
      setState('recording');
      store.pauseRecord();
      store.setStore({ pauseTime: +new Date() });
      start();
    }
  };
  const start = () => {
    timer.current = setInterval(() => {
      store.setStore({ recordTime: store.recordTime + 1000 });
    }, 1000);
  };
  useEffect(() => {
    window.console.log(store.currentRecorder);
  }, [store.recordTime]);
  return (
    <div
      className={styles.content}
      onClick={() => {
        if (store.startTime === 0) {
          store.setStore({
            startTime: +new Date()
          });
        }
        recorderTime();
      }}
    >
      <div>
        {state === 'ready' ? (
          <span>开始</span>
        ) : (
          <span
            onClick={() => {
              if (state === 'end') {
                navigate('/main/home');
                window.api.openMacSwitch();
                store.setStore({
                  recordTime: 0,
                  pauseTime: 0
                });
              }
            }}
          >
            {state === 'pause' ? '继续' : state === 'end' ? '结束' : '暂停'}
          </span>
        )}

        {state === 'pause' && (
          <span
            onClick={(e) => {
              e.stopPropagation();
              store.stopRecord();
              setState('end');
              clearInterval(timer.current);
            }}
          >
            停止
          </span>
        )}
      </div>
      <div>{dayjs.duration(store.recordTime).format('HH:mm:ss')}</div>
    </div>
  );
};

export default observer(Index);
